package net.protocol.diameter.message;

import net.protocol.diameter.avp.AVP;
import net.protocol.diameter.dictionary.AVPRule;
import net.protocol.diameter.dictionary.MessageFormat;

/**
 * @author jinhongw@gmail.com
 */
public class Formatter {

    /**
     * Returns A formatted string of <code>DiameterMessage</code>
     * The string returned is of the form:
     *
     * <pre>
     * Diameter Message:DWA
     * Version: 1
     * Msg Length: 76
     * Cmd Flags: 0
     * Cmd Code: 280
     * App-Id: 0
     * Hop-By-Hop-Id: 3836741727
     * End-To-End-Id: 3836741727
     *   Result-Code (268,M,l=12) = 2001
     *   Origin-Host (264,M,l=25) = nanjing.china.com
     *   Origin-Realm (296,M,l=17) = china.com
     * <pre/>
     *
     * @param format Diameter Message Format
     * @param msg Diameter Message
     * @return A formatted string of <code>AVP</code>
     */
    public static String format(MessageFormat format, DiameterMessage msg) {
        if (format == null) return msg.toString();
        StringBuilder buf = new StringBuilder("Diameter Message:");
        buf.append(format.getName());
        buf.append("\n");
        buf.append("Version: ").append(msg.getVersion()).append("\n");
        buf.append("Msg Length: ").append(msg.getMessageLength()).append("\n");
        buf.append("Cmd Flags: ").append(msg.getCommandFlags()).append("\n");
        buf.append("Cmd Code: ").append(msg.getCommandCode()).append("\n");
        buf.append("App-Id: ").append(msg.getApplicationID()).append("\n");
        buf.append("Hop-By-Hop-Id: ").append(msg.getHopByHopIdentifier()).append("\n");
        buf.append("End-To-End-Id: ").append(msg.getEndToEndIdentifier());

        for (AVP<?> e : msg) {
            AVPRule rule = format.get(e.getVendorId(), e.getCode());
            if (rule == null) {
                buf.append("\n  ").append(e);
            } else {
                String avp = net.protocol.diameter.avp.Formatter.format(rule.getAVPFormat(), e);
                buf.append("\n  ").append(avp);
            }
        }
        return buf.toString();
    }
}
